﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Web.Configuration;
using System.Data.SqlClient;
using System.Text;

public partial class user_control_Cart : System.Web.UI.UserControl
{
    ShopLaptopConnection connect;
    SqlConnection conn;

    protected void Page_Load(object sender, EventArgs e)
    {
        connect = new ShopLaptopConnection();
        conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["ShopLaptopConnectionString"].ConnectionString);
        if (!IsPostBack)
        {
           
            ArrayList listProID = (ArrayList)Session["proID"];

            displayCart(listProID);
       }
    }

    private void RemoveCartById(ArrayList list, int id)
    {
        foreach (ShopCart c in list)
        {
            if (c.ProID == id)
            {
                list.Remove(c);
                break;
            }
        }
    }

    protected void grProduct_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        ArrayList listProID = (ArrayList)Session["proID"];
        //int ProIDRemove = Convert.ToInt32(grProduct.Rows[e.RowIndex].Cells[1].Text);
        int ProIDRemove = Convert.ToInt32(grProduct.DataKeys[e.RowIndex].Value);
        RemoveCartById(listProID, ProIDRemove);
        Session["proID"] = listProID;
        if (Session["proID"] == null)
        {
            Response.Redirect("CartEmpty.aspx");
        }

         displayCart(listProID);
     
    }

    protected void displayCart(ArrayList listProID)
    {
        grProduct.DataSource = "";
        grProduct.DataBind();
        string proIDs = "";

        if (Session["proID"] != null)
        {
            listProID = (ArrayList)Session["proID"];
            foreach (object var in listProID)
            {
                ShopCart newCa = (ShopCart)var;
                if (proIDs == "")
                {
                    proIDs = newCa.ProID.ToString();
                }
                else
                {
                    proIDs += "," + newCa.ProID.ToString();
                }
            }
            //Response.Write(proIDs);
            try
            {
                SqlCommand cmd = new SqlCommand("Select ProID,ProName,ProDesc,ProPrice,ProImage from product where proId in (" + proIDs + ")", conn);
                
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                DataSet ds = new DataSet();
                da.Fill(ds);
                if (ds.Tables[0].Rows.Count > 0)
                {
                    grProduct.DataKeyNames = new string[] { "ProID" };
                    grProduct.DataSource = ds.Tables[0];

                    grProduct.DataBind();
                    int sum = 0;
                    for (int i = 0; i < grProduct.Rows.Count; i++)
                    {
                        int price = Convert.ToInt32(((Label)grProduct.Rows[i].FindControl("Label6")).Text);
                        sum += price;
                    }
                    lbSumPrice.Text = sum.ToString();
                    
                }
                else
                {
                    //lbNoData.Text = "No data in your ShopCart";
                }

            }
            catch (Exception ex)
            {
                
            }
            
        }
        
    }

    int stt = 1;
    public string STT()
    {
        return Convert.ToString(stt++);
    }

    public int GetSoLuongByProId(object proID)
    {
        int soLuong=1;
        ArrayList listProID = new ArrayList();
        listProID.AddRange((ArrayList)Session["proID"]);
        foreach (object a in listProID)
        {
            ShopCart newCa = (ShopCart)a;
            if (newCa.ProID == Convert.ToInt32(proID))
            {
                soLuong=newCa.SoLuong;
            }
        }
        return soLuong;
    }


    
    protected void grProduct_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        ArrayList listProID = (ArrayList)Session["proID"];
        grProduct.PageIndex = e.NewPageIndex;   //trang hien tai
        int trang_thu = e.NewPageIndex;      //the hien trang thu may
        int so_dong = grProduct.PageSize;       //moi trang co bao nhieu dong
        stt = trang_thu * so_dong + 1;
        displayCart(listProID);
    }
   

    private void ShowPopUpMsg(string msg)
    {
        StringBuilder sb = new StringBuilder();
        sb.Append("alert('");
        sb.Append(msg.Replace("\n", "\\n").Replace("\r", "").Replace("'", "\\'"));
        sb.Append("');");
        ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "showalert", sb.ToString(), true);
    }
    protected void TextBox1_TextChanged(object sender, EventArgs e)
    {
        //TextBox txt = (TextBox)grProduct.Rows[grProduct.SelectedIndex].FindControl("TextBox1");
        //Response.Write(txt.Text);

    }

    private float GetPriceByProId(float proID)
    {
        float Price = 0;
        SqlDataAdapter da = new SqlDataAdapter("Select ProPrice from Product where proID=" + proID, conn);
        DataTable dt = new DataTable();
        da.Fill(dt);
        if (dt.Rows.Count > 0)
        {
            Price = Convert.ToInt32(dt.Rows[0]["ProPrice"]);
        }
        return Price;
    }

    public float GetTotalPrice(object proID)
    {
        float id = Convert.ToInt32(proID);
        float price = GetPriceByProId(id);
        float soluong = GetSoLuongByProId(proID);
        return soluong * price;
    }
    protected void lbtnOtherAdd_Click(object sender, EventArgs e)
    {
        
        pnOtherAdd.Visible = true;
        
    }
    


    protected void ibtnUpdate_Click(object sender, ImageClickEventArgs e)
    {
        ArrayList listProID = (ArrayList)Session["proID"];

        try
        {
            
            for (int i = 0; i < grProduct.Rows.Count; i++)
            {
                foreach (ShopCart ca in listProID)
                {

                    if (ca.ProID == Convert.ToInt32(grProduct.DataKeys[i].Value))
                    {
                        int sl = Convert.ToInt32(((TextBox)grProduct.Rows[i].FindControl("Textbox1")).Text);
                        if (sl > 0)
                        {
                            ca.SoLuong = sl;
                        }
                        else
                        {
                            listProID.Remove(ca);
                            break;
                        }
                    }
                }
            }
            Session["proID"] = listProID;
            displayCart(listProID);
            
        }
        catch
        {
            for (int i = 0; i < grProduct.Rows.Count; i++)
            {
                foreach (ShopCart ca in listProID)
                {

                    if (ca.ProID == Convert.ToInt32(grProduct.DataKeys[i].Value))
                    {
                        ((TextBox)grProduct.Rows[i].FindControl("Textbox1")).Text = ca.SoLuong.ToString();
                        
                    }
                }
            }
        }
    }
    protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
    {
        Response.Redirect("Default.aspx");
    }
    protected void ImageButton3_Click(object sender, ImageClickEventArgs e)
    {
        if (Session["proID"] == null)
        {
            ShowPopUpMsg("Khong co san pham nao trong gio hang!");
            return;
        }
        ArrayList CartProducts = (ArrayList)Session["proID"];

        Customer cus = (Customer)Session["Customer"];

        if (cus == null)
        {
            ShowPopUpMsg("You must to login.");
            return;
        }
       
        SqlCommand cmd = new SqlCommand();
        cmd.Connection = conn;

        try
        {
            conn.Open();
            int check = 0;

            check = connect.InsertOrders(cus.CusName, cus.CusAdd, cus.CusPhone, int.Parse(drdlPayment0.SelectedValue), cus.CusID);
            if (check > 0)
            {
                cmd.CommandText = "Select Max(OrdID) From orders";
                int maxid = -1;
                maxid = (int)cmd.ExecuteScalar();
                foreach (ShopCart ca in CartProducts)
                {
                    float price = GetPriceByProId(ca.ProID);
                    connect.InsertOrderDetail(maxid, ca.ProID, ca.SoLuong, price);
                }
                ShowPopUpMsg("Ban da dat hang thanh cong!");
            }
            conn.Close();
        }
        catch (Exception)
        {

            conn.Close();
        }
        finally
        {
            try
            {
                conn.Close();
            }
            catch (Exception)
            {


            }
        }
    }
    protected void ImageButton4_Click(object sender, ImageClickEventArgs e)
    {
        if (Session["proID"] == null)
        {
            ShowPopUpMsg("Khong co san pham nao trong gio hang!");
            return;
        }
        ArrayList CartProducts = (ArrayList)Session["proID"];

        Customer cus = (Customer)Session["Customer"];
        if (cus == null)
        {
            ShowPopUpMsg("You must to login.");
            return;
        }

        if (txtName.Text.Equals("") || txtAddress.Text.Equals(""))
        {
            ShowPopUpMsg("Name and address is not blank!");
            return;
        }


        SqlCommand cmd = new SqlCommand();
        cmd.Connection = conn;

        try
        {
            conn.Open();
            int check = 0;

            check = connect.InsertOrders(txtName.Text, txtAddress.Text, txtPhone.Text, int.Parse(drdlPayment.SelectedValue), cus.CusID);
            if (check > 0)
            {
                cmd.CommandText = "Select Max(OrdID) From orders";
                int maxid = -1;
                maxid = (int)cmd.ExecuteScalar();
                foreach (ShopCart ca in CartProducts)
                {
                    float price = GetPriceByProId(ca.ProID);
                    connect.InsertOrderDetail(maxid, ca.ProID, ca.SoLuong, price);
                }
                ShowPopUpMsg("Ban da dat hang thanh cong!");
            }
            conn.Close();
        }
        catch (Exception)
        {

            conn.Close();
        }
        finally
        {
            try
            {
                conn.Close();
            }
            catch (Exception)
            {


            }
        }
    }
    protected void ibtnRemoveSelection_Click(object sender, ImageClickEventArgs e)
    {
        ArrayList listProID = (ArrayList)Session["proID"];
        if (grProduct.Rows.Count > 0)
        {
            
            for (int i = 0; i < grProduct.Rows.Count; i++)
            {
                CheckBox chk = (CheckBox)grProduct.Rows[i].FindControl("chkRemove");
                if (chk.Checked)
                {
                    int id = Convert.ToInt32(grProduct.DataKeys[i].Value);
                    RemoveCartById(listProID, id);
                    
                }
            }
        }
        displayCart(listProID);
        Session["proID"] = listProID;
    }
}
